package com.valveinspectionsys.settingsys.activity;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.valveinspectionsys.MainActivity;
import com.valveinspectionsys.R;
import com.valveinspectionsys.dbhelp.XmlNameHelper;
import com.valveinspectionsys.httpserver.HttpClientServer;
import com.valveinspectionsys.httpserver.RequestUrl;
import com.valveinspectionsys.settingsys.db.SettingDao;
import com.valveinspectionsys.util.SharedPreferenceUtil;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * 与服务连接配制
 * @author king
 *
 */
public class WebActivity extends Activity implements OnClickListener {
       public Button button1;//检测
       public Button button2;//保存
       public EditText edit1;//IP
       public EditText edit2;//端口
       public EditText edit3;//水司代码
       
       public SettingDao dao;
       
       public ProgressDialog pd;
       
       public SharedPreferenceUtil sh;
       
       private final static int DIALOG = 1;
       
       public InputMethodManager imm;
       
    @Override
    protected void onCreate(Bundle savedInstanceState) {
	
	super.onCreate(savedInstanceState);
	setContentView(R.layout.settingsys_web);

//	// 解决android 4.0Http请求问题
//	StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
//	StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath().build());
	dao=new SettingDao(this);
	sh=new SharedPreferenceUtil(this);
        imm=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
	initUi();
    }

    //初始化UI控件
    public void initUi(){
	button1=(Button)findViewById(R.id.setting_web_check);
	button2=(Button)findViewById(R.id.setting_web_ok);	
	edit1=(EditText)findViewById(R.id.setting_web_id);
	edit2=(EditText)findViewById(R.id.setting_web_port);
	edit3=(EditText)findViewById(R.id.setting_DivisionCode);
	String[] s=dao.queryWebSeting();
	edit1.setText(s[0]);
	edit2.setText(s[1]);
	edit3.setText(s[2]);
	button1.setOnClickListener(this);
	button2.setOnClickListener(this);
	
    }

    @Override
    public void onClick(View v) {
	switch (v.getId()) {
	case R.id.setting_web_check:
	       if(!TextUtils.isEmpty(edit1.getEditableText().toString())&&!TextUtils.isEmpty(edit2.getEditableText().toString())&&
		       !TextUtils.isEmpty(edit3.getEditableText().toString())){
		      pd=new ProgressDialog(this);
	              pd.setMessage("正在连接服务器......");
	              pd.show();
	              new Thread(){

			@Override
			public void run() {
			    ConnectServer();
			    super.run();
			}
	        	  
	              }.start();
	            
	       }else{
		   Toast.makeText(WebActivity.this, "不能有空！", Toast.LENGTH_SHORT).show();
	       }
	            
	    break;
	case R.id.setting_web_ok:
	    if(!sh.getBoolean(XmlNameHelper.CHECKSERVERCONNECT)){
	  		showDialog(DIALOG);
	  		return ;
	  	    }
	    Intent intent=new Intent(WebActivity.this, MainActivity.class);
	    setResult(RESULT_OK,intent);
	    finish();
	    break;
	default:
	    break;
	}
	
    }

    //连接服务器
    public boolean ConnectServer(){
	
	HttpClientServer server=new HttpClientServer(this);
	Map<String, String> map=new HashMap<String, String>();
	map.put("message", "message");
	String url="http://"+edit1.getEditableText().toString()+":"+edit2.getEditableText().toString()+
		"/"+edit3.getEditableText().toString()+RequestUrl.CheckConnect;
	String respone=server.doPost(map, url,false);
	try {
	    JSONObject json=new JSONObject(respone);
	    String code=json.getString("code");
	    if(!code.equals("1")){
		   Message msg=myHandler.obtainMessage();
		   msg.what=0;
		   myHandler.sendMessage(msg);
		    return false;
		}
		Message msg=myHandler.obtainMessage();
		msg.what=1;
		myHandler.sendMessage(msg);
		
	} catch (JSONException e) {
	    return false;
	   
	}
	
	return true;
	
    }
    @Override
    protected Dialog onCreateDialog(int id) {
	Dialog dialog = null;
	switch (id) {
	case DIALOG:
	    Builder builder = new android.app.AlertDialog.Builder(this);
	    // 设置对话框的图标
	    builder.setIcon(R.drawable.buttondraw);
	    // 设置对话框的标题
	    builder.setTitle("提示信息");
	    builder.setMessage("确定要退出抄表系统吗？");
	    // 0: 默认第一个单选按钮被选中
	    builder.setPositiveButton("确定", new DialogInterface. OnClickListener() {
	        
	        @Override
	        public void onClick(DialogInterface dialog, int which) {
	            Intent intent = new Intent();   
	            intent.setAction("com.app.exit"); // 退出动作   
	            sendBroadcast(intent);// 发送广播   
	            finish();
	    	
	        }
	    });
	    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
	        
	        @Override
	        public void onClick(DialogInterface dialog, int which) {
	            dialog.dismiss(); 
	    	
	        }
	    });
	    
	    dialog=builder.create();
	    break;

	default:
	    break;
	}
	return dialog;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
	if(keyCode==KeyEvent.KEYCODE_BACK){
	    if(!sh.getBoolean(XmlNameHelper.CHECKSERVERCONNECT)){
		showDialog(DIALOG);
		return false;
	    }else {
		if(!imm.isActive()){
		    
		    Intent intent=new Intent(WebActivity.this, MainActivity.class);
		    setResult(RESULT_OK,intent);
		    finish();
		}
	    }
	}
	
	return super.onKeyUp(keyCode, event);
    }
    
    Handler myHandler=new Handler(){

	@Override
	public void handleMessage(Message msg) {
	    if(msg.what==1){
		pd.dismiss();
		Toast.makeText(WebActivity.this, "连接服务器成功！", Toast.LENGTH_SHORT).show();
		sh.insertValue(XmlNameHelper.CHECKSERVERCONNECT, true);
		sh.insertValue(XmlNameHelper.IP, edit1.getEditableText().toString());
		sh.insertValue(XmlNameHelper.port, edit2.getEditableText().toString());
		sh.insertValue(XmlNameHelper.webName, edit3.getEditableText().toString());
	    }else if(msg.what==0){
		        pd.dismiss();
		    Toast.makeText(WebActivity.this, "输入有误，连接服务器失败", Toast.LENGTH_SHORT).show();
		    sh.insertValue(XmlNameHelper.CHECKSERVERCONNECT, false);
		    edit1.setText(sh.getValue(XmlNameHelper.IP));
		    edit2.setText(sh.getValue(XmlNameHelper.port));
		    edit3.setText(sh.getValue(XmlNameHelper.webName));
	    }
	    super.handleMessage(msg);
	}
	
    };
}
